package com.guochaojava.websocket;

import cn.hutool.core.lang.Console;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class MyHandler extends TextWebSocketHandler {
    /**
     * 在线用户列表
     */
    private static final Map<String, WebSocketSession> users;
    /**
     * 用户标识
     */
    private static final String CLIENT_ID = "info";

    static {
        users = new HashMap<>();
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("成功建立连接");
        String info = getInfo(session);
        Console.log(info);
        if (info != null) {
            WebSocketSession webSocketSession = users.get(info);
            if (webSocketSession == null) {
                users.put(info, session);
            }
            session.sendMessage(new TextMessage("成功建立socket连接"));
        }
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        // ...
        System.out.println(message.getPayload());

        WebSocketMessage message1 = new TextMessage("server:" + message);
        try {
            session.sendMessage(message1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送信息给指定用户
     *
     * @param info    标识
     * @param message 消息体
     * @return 发送结果
     */
    public boolean sendMessageToUser(String info, TextMessage message) {
        if (users.get(info) == null) {
            return false;
        }
        WebSocketSession session = users.get(info);
        if (!session.isOpen()) {
            return false;
        }
        try {
            session.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 广播信息
     *
     * @param message 消息体
     * @return 发送结果
     */
    public boolean sendMessageToAllUsers(TextMessage message) {
        boolean allSendSuccess = true;
        if (users != null) {
            Set<String> openIds = users.keySet();
            WebSocketSession session = null;
            for (String openId : openIds) {
                try {
                    session = users.get(openId);
                    if (session.isOpen()) {
                        session.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    allSendSuccess = false;
                }
            }

        }

        return allSendSuccess;
    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        System.out.println("连接出错");
        String info = getInfo(session);
        Set<String> openIds = users.keySet();
        for (String openId : openIds) {
            if (session == users.get(openId)) {
                users.remove(openId);
            }
        }
        users.remove(info);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接已关闭：" + status);
        String info = getInfo(session);
        Set<String> openIds = users.keySet();
        for (String openId : openIds) {
            if (session == users.get(openId)) {
                users.remove(openId);
            }
        }
        users.remove(info);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 获取用户标识
     *
     * @param session
     * @return 用户标识
     */
    private String getInfo(WebSocketSession session) {
        try {
            String info = (String) session.getAttributes().get(CLIENT_ID);
            return info;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}